package com.chanzany.srb.oos.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.chanzany.srb.oos.service.FileService;
import com.chanzany.srb.oos.util.OssProperties;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.UUID;

/**
 * @Author ChanZany
 * @Date 2021/4/14 12:55
 * @Version 1.0
 */
@Service
public class FileServiceImpl implements FileService {
    @Override
    public String upload(InputStream inputStream, String module, String fileName) {
        //创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(
                OssProperties.ENDPOINT,
                OssProperties.KEY_ID,
                OssProperties.KEY_SECRET
        );

        //判断BUCKET是否存在，不存在就创建
        if (!ossClient.doesBucketExist(OssProperties.BUCKET_NAME)) {
            ossClient.createBucket(OssProperties.BUCKET_NAME);
            ossClient.setBucketAcl(OssProperties.BUCKET_NAME, CannedAccessControlList.PublicRead);
        }
        //构建日期路径
        String timeFolder = new DateTime().toString("/yyyy/MM/dd/");
        //构建新的文件名
        fileName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
        //文件路径
        String savePath = module + timeFolder + fileName;
        //上传到阿里云
        ossClient.putObject(OssProperties.BUCKET_NAME, savePath, inputStream);
        ossClient.shutdown();
        //返回该文件的下载url:https://sangrongbao-file.oss-cn-hangzhou.aliyuncs.com/test.txt
        return "https://" + OssProperties.BUCKET_NAME + "." + OssProperties.ENDPOINT + "/" + savePath;
    }

    @Override
    public void removeFile(String url) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(
                OssProperties.ENDPOINT,
                OssProperties.KEY_ID,
                OssProperties.KEY_SECRET);
        //拿到文件名称 https://sangrongbao-file.oss-cn-hangzhou.aliyuncs.com/test.txt
        String host = "https://"+OssProperties.BUCKET_NAME+"."+OssProperties.ENDPOINT+"/";
        String objectName = url.substring(host.length());
        // 删除文件。
        ossClient.deleteObject(OssProperties.BUCKET_NAME,objectName);
        ossClient.shutdown();
    }
}
